<?php
/*
	申请成为代理商
	如果已申请，但尚未审核通过，则页面显示请耐心等待管理员审核！
	如果已申请，且审核通过，则显示审核通过，并提供按钮前往代理中心
	如果审核不通过，则显示审核不通过原因
*/
defined('BY_JYA') or exit('error');
$_RQ['op']=$_RQ['op']?$_RQ['op']:'main';
cfc('core')->checklogin();
if($_RQ['op']=='main'){
	set_html('title','申请成为代理');
	$member=$this->pdo_get('member',array('merchid'=>$_SESSION['onemerchid'],'mid'=>$_SESSION['uid']));
	$apply=$this->get('apply',array('merchid'=>$_SESSION['onemerchid'],'mid'=>$_SESSION['uid']));
	if($apply['status']==1 && $member['is_agent']!=1){
		pdo_delete('jy_merch2fee_apply',array('merchid'=>$_SESSION['onemerchid'],'uniacid'=>$_SESSION['uniacid'],'mid'=>$_SESSION['uid']));
	}
	if($apply['id']){
		$return['apply']=$apply;
		$return['applystatus']=$apply['status'];
	}
	//判断是否满足申请分销商条件
	$can_apply=true;
	$applyres=$this->model('member')->up_apply($member);
	$return['now']=$applyres['now'];
	$return['limit']=$applyres['limit'];
	$return['unit']=$applyres['unit'];
	$return['can_apply']=$applyres['can_apply'];
	$return['become_goods']=$applyres['become_goods'];
	$return['member']=$member;
	if($member['agent_id']){
		$return['agent']=model('core/member')->detail($member['agent_id'],array('nickname','avatar'));
		$return['agent_name']=$return['agent']['nickname'];
	}
	$setting=$this->plugin_setting('page_setting');
	$return['setting']=$setting;
	if($_SESSION['onemerchid']){
		$return['applyset']=$this->plugin_setting('apply'.$_SESSION['onemerchid']);
	}else{
		$return['applyset']=$this->plugin_setting('apply');
	}
	$return['member']=$member?:false;
	$return['item']=model('core/member')->detail($_SESSION['uid'],array('nickname','avatar','realname','mobile','wechat'));
	$return['item']['diyformfields']=$setting['diyformfields']?:array();
	$indexurl=$_SESSION['onemerchid']?'jy_merch/merch/':'jy_weishop/index/';
	$return['indexurl']=$_SESSION['indexurl']?:$indexurl;
	exi($return);
}
if($_RQ['op']=='apply'){
	$post=get_postdata();
	if(!$post['agree']){
		exi('请先阅读协议！','error');
	}
	if(!$post['realname']){
		exi('请输入姓名！','error');
	}
	if(!$post['mobile']){
		exi('请输入联系电话！','error');
	}
	$member_update=array(
		'realname'=>trim($post['realname']),
		'mobile'=>trim($post['mobile']),
		'diyformdata'=>ijson_encode($post['diyformfields']),
	);
	if($post['wechat']){
		$member_update['wechat']=trim($post['wechat']);
	}
	$this->model('member')->member_update($_SESSION['uid'],$member_update);	
	$this->model('member')->apply_agent($_SESSION['uid']);
	if($post['agent_id']){
		$this->model('member')->set_parent($_SESSION['uid'],$post['agent_id']);
	}
	exi('申请成功！请耐心等待管理员审核！','','main');
}